<template>
  <div class="crud-table">
    <slot />
  </div>
</template>

<script>
import { TYPE_LIST } from '../token'
import { checkUnSetUrlError, type } from '../utils'

const paginationDefault = {
  enablePagination: () => false,
  currentPage: () => 1,
  defaultPageSize: () => 15,
  setTotal: () => { },
  setCurrentPage: () => { },
}

export default {
  name: 'crud-table-v2',
  props: {
    url: String,
    params: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      tableData: [],
      isLoading: false,
      fieldCache: {},
      $_pagination: {},
    }
  },
  provide() {
    return {
      tableData: () => this.tableData,
      isLoading: () => this.isLoading,
      getTableDatas: this.getTableData,
      setField: this.appendParams,
      resetTableData: (params) => {
        this.appendParams(params)
        this.getTableData(true)
      },
      useBridge: (...args) => this.bridge(...args)
    }
  },
  methods: {
    async getTableData(resetPageNo = true, params = {}) {
      if (!(checkUnSetUrlError(TYPE_LIST, this.url))) return

      const { currentPage, enablePagination, defaultPageSize, setTotal, setCurrentPage } = this.$_pagination || paginationDefault
      if (resetPageNo && currentPage()) {
        setCurrentPage(1)
      }
      this.isLoading = true
      const requestKeys = this.$data.$_requestKeys
      try {
        const res = await this.$_request({
          url: this.url,
          method: 'GET',
          params: Object.assign(
            enablePagination() ? {
              [requestKeys.pageKey]: currentPage(),
              [requestKeys.sizeKey]: defaultPageSize()
            } : {}, Object.assign(params, this.params, this.fieldCache))
        })
        // todo 确定 params 调用方法传递的参数， this.params 表格默认参数， this.fieldCache 缓存的参数（搜索表单的参数），三个的合并优先级（存在同名参数覆盖的问题）
        if (enablePagination()) {
          const { [requestKeys.dataKey]: records, [requestKeys.totalKey]: resTotal } = res.data

          if (!records && !resTotal) return console.error("接口响应数据格式不合法")

          this.tableData = records
          setTotal(resTotal)
        } else {
          if (!res.data || type(res.data) !== 'array') return console.error(`接口响应数据格式不合法，[data]要求是array，但是得到了${type(res.data)}`)
          this.tableData = res.data
        }
        this.$emit('loaded', { data: this.tableData, requestParams: { ...this.fieldCache, ...this.params } })
      } finally {
        // await this.$nextTick()
        this.isLoading = false
      }
    },
    appendParams(obj) {
      for (const key in obj) {
        this.fieldCache[key] = obj[key]
      }
    },
    bridge(_name, evt) {
      switch (_name) {
        case 'showDialog':
          const comp = this.$children.find(x => x.$options.name === 'CrudTableDialog')
          if (comp) comp.open(evt)
          break;
        default:
          break;
      }
    },
  },
}
</script>
